package net.hserver.admin.system.controller;
import cn.dev33.satoken.stp.StpUtil;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.plugin.web.annotation.Controller;
import cn.hserver.plugin.web.annotation.GET;
import cn.hserver.plugin.web.annotation.POST;
import cn.hserver.plugin.web.interfaces.HttpRequest;
import cn.hserver.plugin.web.interfaces.HttpResponse;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import lombok.extern.slf4j.Slf4j;
import net.hserver.admin.system.common.MyCode;
import net.hserver.admin.system.common.MyResult;
import net.hserver.admin.system.config.CacheConfig;
import net.hserver.admin.system.config.Log;
import net.hserver.admin.system.dto.LoginDTO;
import net.hserver.admin.system.entity.User;
import net.hserver.admin.system.service.UserService;
import net.hserver.admin.system.utils.RsaUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 鉴权接口
 *
*
 * @since 2022-06-12
 */
@Slf4j
@Controller("/")
@Log
public class AuthController {
    @Autowired
    private UserService userService;

    /**
     * 登陆
     *
     * @param user    登陆信息
     * @param request request
     */
    @POST("login")
    public MyResult login(LoginDTO user, HttpRequest request) {

        if (user.getCaptchaId()==null){
            throw MyCode.ERROR_CAPTCHA.toException();
        }

        GifCaptcha captcha = CacheConfig.CAPTCHA_CODE.getIfPresent(user.getCaptchaId());
        if (captcha == null) {
            throw MyCode.ERROR_CAPTCHA.toException();
        }
        log.info("verify captcha: {} - {} [{}]", user.getCaptcha(), captcha.getCode(), captcha.verify(user.getCaptcha()));
        if (!captcha.verify(user.getCaptcha())) {
            throw MyCode.ERROR_CAPTCHA.toException();
        }

        String username = user.getUsername();
        String password = user.getPassword();
        Optional<User> opt = userService.getByUsername(username);
        if (opt.isPresent()) {
            User info = opt.get();
            if (RsaUtil.decrypt(info.getPassword()).equals(password)) {
                if (info.getLocked()) {
                    throw MyCode.LOCKED_ACCOUNT.toException();
                }
                StpUtil.login(info.getUserId());
            } else {
                throw MyCode.ERROR_PASSWORD.toException();
            }
        } else {
            throw MyCode.UNKNOWN_ACCOUNT.toException();
        }
        return MyResult.of(StpUtil.getTokenInfo());
    }

    /**
     * 登出
     */
    @POST("logout")
    public MyResult logout() {
        StpUtil.logout();
        return MyResult.success();
    }

    /**
     * 获取当前登录用户信息
     */
    @GET("current")
    public MyResult getCurrent() {
        Long loginId = StpUtil.getLoginIdAsLong();
        return MyResult.of(userService.getById(loginId));
    }

    /**
     * 获取验证码
     *
     * @param response 验证码
     * @param request  request
     * @throws IOException IOException
     */
    @GET("captcha")
    public MyResult captcha(HttpResponse response, HttpRequest request) throws IOException {
        RandomGenerator generator = new RandomGenerator("23456789abdefghjmnqrtABDEFGHJMNQRT", 4);
        GifCaptcha captcha = CaptchaUtil.createGifCaptcha(200, 100, 4);
        captcha.setGenerator(generator);
        captcha.createCode();
        UUID uuid = UUID.randomUUID();
        CacheConfig.CAPTCHA_CODE.put(uuid.toString(), captcha);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        captcha.write(out);
        String s = Base64.getEncoder().encodeToString(out.toByteArray());
        Map<String,Object> map = new HashMap<>();
        map.put("captchaId", uuid.toString());
        map.put("captcha",s);
        return MyResult.of(map);
    }
}
